<template>
    <a-layout-header class="header">
        <div class="logo">
            危废品管理后台
        </div>
        <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent style="float: right;font-size: 18px">
                <img v-if="loginUser.headPicture" :src="loginUser.headPicture"
                     class="pic"/>
                <img v-else src="https://lyj-mall-bucket.oss-cn-guangzhou.aliyuncs.com/20230129/default.png"
                     class="pic"/>
                {{loginUser.name}}
                <DownOutlined/>
            </a>
            <template #overlay>
                <a-menu>
                    <a-menu-item @click="openUpdatePasswordModal">
                        修改密码
                    </a-menu-item>
                    <a-menu-item @click="switchAvatars">
                        切换头像
                    </a-menu-item>
                    <a-menu-item @click="logout">
                        退出登录
                    </a-menu-item>
                    <a-menu-item @click="connectTest">
                        测试权限
                    </a-menu-item>
                </a-menu>
            </template>
        </a-dropdown>
    </a-layout-header>
    <a-modal v-model:visible="visible" title="修改密码" @ok="handleOk">
        <a-form
                :model="passwordData"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 18 }"
        >
            <a-form-item
                    label="原始密码"
                    name="oldPassword"
                    :rules="[{ required: true, message: '请输入原始密码!' }]"
            >
                <a-input v-model:value="passwordData.oldPassword"/>
            </a-form-item>

            <a-form-item
                    label="新密码"
                    name="newPassword"
                    :rules="[{ required: true, message: '请输入新的密码!' }]"
            >
                <a-input-password v-model:value="passwordData.newPassword"/>
            </a-form-item>
        </a-form>
    </a-modal>
    <a-modal v-model:visible="visibleSwitch" title="切换头像" @ok="switchOk" style="text-align: center">
        <a-upload
                v-model:file-list="fileList"
                name="file"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                action="http://localhost:8086/upload/uploadAvatar"
                :before-upload="beforeUpload"
                @change="handleChange"
        >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar"
                 style="width: 100px;height: 100px;border-radius: 50%"/>
            <div v-else>
                <loading-outlined v-if="loading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">Upload</div>
            </div>
        </a-upload>
    </a-modal>
</template>

<script>
    import {ref, onMounted, onBeforeMount} from 'vue'
    import {DownOutlined, LoadingOutlined, PlusOutlined} from '@ant-design/icons-vue';
    import {message} from 'ant-design-vue'
    import {SessionStorage} from '../../public/session-storage'
    import axios from 'axios'
    import cookies from 'js-cookie'
    import {useRouter} from 'vue-router'
    import Cookies from "js-cookie";

    export default {
        name: "Header",
        components: {
            DownOutlined,
            LoadingOutlined,
            PlusOutlined,
        },
        setup() {
            const loginUser = ref();
            const router = useRouter()
            const visible = ref(false)
            const visibleSwitch = ref(false)
            const passwordData = ref({})

            const openUpdatePasswordModal = () => {
                visible.value = true
                passwordData.value.id = loginUser.value.id
            }

            const handleOk = () => {
                console.log("修改密码的数据：", passwordData.value)
                axios.post('/updatePassword', passwordData.value).then(rs => {
                    if (rs.data.code == 200) {
                        message.info("密码修改成功")
                        logout()
                    } else {
                        message.error(rs.data.message)
                    }
                })
            }

            const switchAvatars = () => {
                console.log("切换头像")
                visibleSwitch.value = true
                imageUrl.value = ''
            }

            const switchOk = () => {
                axios.get('/sys-user/switchAvatar', {
                    params: {
                        id: loginUser.value.id,
                        headPicture: imageUrl.value
                    }
                }).then(rs => {
                    if (rs.data.code == 200) {
                        message.success("头像切换成功")
                        loginUser.value = rs.data.data
                        Cookies.set("user", JSON.stringify(rs.data.data), { expires: 0.2 }); //单位天
                        visibleSwitch.value = false
                    } else {
                        message.error(rs.data.message)
                    }
                })
                console.log("")
            }

            const fileList = ref([]);
            const loading = ref(false);
            const imageUrl = ref('');

            const handleChange = info => {
                if (info.file.status === 'uploading') {
                    console.log("上传uploading信息：", info)
                    loading.value = true;
                    return;
                }
                if (info.file.status === 'done') {
                    console.log("上传done信息：", info)
                    imageUrl.value = info.file.response
                    loading.value = false
                }
                if (info.file.status === 'error') {
                    console.log("上传error信息：", info)
                    loading.value = false;
                    message.error('upload error');
                }
            };

            const beforeUpload = file => {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                    message.error('You can only upload JPG file!');
                }
                const isLt5M = file.size / 1024 / 1024 < 5;
                if (!isLt5M) {
                    message.error('Image must smaller than 5MB!');
                }
                return isJpgOrPng && isLt5M;
            };

            const logout = () => {
                SessionStorage.clearAll()
                cookies.remove('user');
                message.info("退出登录")
                router.push('/')
            }

            const connectTest = () => {
                axios.get('/testPermission').then(rs => {
                    console.log("测试连接结果：", rs)
                    if (rs.data.code == 200){
                        message.success("拥有权限,连接成功")
                    }else {
                        message.error(rs.data.message)
                    }
                })
            }

            // onMounted(()=>{
            //     loginUser.value = SessionStorage.get("loginUser")
            //     console.log("登录的用户",loginUser)
            // })
            onBeforeMount(() => {
                loginUser.value = JSON.parse(cookies.get('user'))
            })

            return {
                openUpdatePasswordModal,
                switchAvatars,
                logout,
                loginUser,
                connectTest,
                visible,
                passwordData,
                handleOk,
                visibleSwitch,
                switchOk,
                fileList,
                loading,
                imageUrl,
                handleChange,
                beforeUpload,
            }
        }
    }
</script>

<style scoped>
    .logo {
        float: left;
        width: 200px;
        color: white;
        font-size: 18px;
    }

    .pic {
        width: 50px;
        height: 50px;
        border-radius: 50%;
    }
</style>